<template>
  <el-dialog
    class="register-dialog"
    width="603px"
    center
    title="用户注册"
    :visible.sync="dialogFormVisible"
  >
    <!-- 绑定表单验证规则 和 起名字  status-icon-是否在输入框中显示校验结果反馈图标-->
    <el-form status-icon :model="form" :rules="rules" ref="registerForm">
      <el-form-item label="头像" prop="avatar">
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          name="image"
        >
          <!-- 根据接口 name 设置为image -->
          <!-- imageUrl 有值 显示图片 -->
          <img :src="imageUrl" class="avatar" v-if="imageUrl" alt />
          <!-- imgageUrl 没有值 显示i 标签 -->
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <!-- v-model 用来绑定属性 prop 用来绑定验证属性 -->
      <el-form-item label="昵称" :label-width="formLabelWidth" prop="username">
        <el-input v-model="form.username" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
        <el-input v-model="form.email" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="手机" :label-width="formLabelWidth" prop="phone">
        <el-input v-model="form.phone" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
        <el-input v-model="form.password" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="图形码" prop="code" :label-width="formLabelWidth">
        <el-row>
          <el-col :span="16">
            <el-input v-model="form.code" autocomplete="off"></el-input>
          </el-col>
          <el-col :span="7" class="register-box" :offset="1">
            <!-- 绑定属性 -->
            <img @click="changeCode" class="register-code" :src="codeURL" alt />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="验证码" prop="rcode" :label-width="formLabelWidth">
        <el-row>
          <el-col :span="16">
            <el-input v-model="form.rcode" autocomplete="off"></el-input>
          </el-col>
          <el-col :span="7" :offset="1">
            <!-- 点击 获取 短信验证码 -->
            <el-button :disabled="delay != 0" @click="getSMS">
              {{
              delay == 0 ? "点击获取验证码" : `还有${delay}秒继续获取`
              }}
            </el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitForm('registerForm')">确 定</el-button>
      <el-button @click="reset('registerForm')">重 置</el-button>
    </div>
  </el-dialog>
</template>

<script>
// 导入 axios
// import axios from "axios";
// 导入 接口
import { sendsms, register } from "@/api/register.js";
// 导入验证 手机 邮箱规则
import { checkEmail, checkPhone } from '@/utils/validator';
export default {
  props: {},
  data () {
    return {
      // 是否显示对话框
      dialogFormVisible: false,
      //   表单数据
      form: {
        // 用户名
        username: "",
        // 密码
        password: "",
        // 邮箱
        email: "",
        // 手机
        phone: "",
        // 图形码
        code: "",
        // 验证码
        rcode: "",
        // 用户头像地址
        avatar: ""
      },
      // 校验规则
      rules: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
          { min: 6, max: 12, message: "用户名长度为6到12位", trigger: "blur" }
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          { min: 6, max: 12, message: "密码长度为6到12", trigger: "blur" }
        ],
        // 自定义的手机验证规则
        phone: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          { validator: checkPhone, trigger: "blur" }
        ],
        email: [
          { required: true, message: "邮箱不能为空", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        avatar: [
          { required: true, message: "图片不能为空", trigger: "blur" }
        ]
      },
      //   左侧文本宽度
      formLabelWidth: "62px",
      // 验证码图片地址
      codeURL: process.env.VUE_APP_URL + "/captcha?type=sendsms",
      // 倒计时时间
      delay: 0,
      // 本地图片预览地址
      imageUrl: "",
      // 头像上传接口地址
      uploadUrl: process.env.VUE_APP_URL + "/uploads"
    };
  },
  computed: {},
  created () { },
  mounted () { },
  watch: {},
  methods: {
    // 重置表单
    reset (formName) {
      this.$refs[formName].resetFields()
      // 人为清空
      this.imageUrl = ''
    },
    // 头像上传成功
    handleAvatarSuccess (res, file) {
      // URL.createObjectURL 生成的是临时途径
      this.imageUrl = URL.createObjectURL(file.raw);
      // 保存 服务器返回图片地址
      this.form.avatar = res.data.file_path;
      // 从新人为校验 validateField --框架自带的验证
      this.$refs.registerForm.validateField("avatar");
    },
    // 上传之前
    beforeAvatarUpload (file) {
      const isJPG = file.type === "image/jpeg" || "image/png" || 'image/gif';
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传的图片格式不对");
      }
      if (!isLt2M) {
        this.$message.error("上传的图片大小不能超过2m");
      }
      return isJPG && isLt2M;
    },
    // 点击获取验证码
    changeCode () {
      // 重新生成 验证码
      // 随机数 或者用时间戳
      this.codeURL =
        process.env.VUE_APP_URL + "/captcha?type=sendsms&t=" + Date.now();
    },
    // 点击获取短息验证码
    getSMS () {
      // 发送之前先判断 手机号和验证码是够正确 避免浪费服务器的性能
      const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
      if (!reg.test(this.form.phone)) {
        return this.$message.error("手机号格式不对, 请重新输入");
      }
      if (this.form.code.length != 4) {
        return this.$message.error("验证码长度不对,从新点击获取");
      }

      // 设置短信验证码 倒计时
      if (this.delay == 0) {
        this.delay = 6;
        const interId = setInterval(() => {
          this.delay--;
          if (this.delay == 0) {
            clearInterval(interId);
          }
        }, 1000);
      }
      // 调用接口
      sendsms({
        code: this.form.code,
        phone: this.form.phone
      }).then(res => {
        //成功回调
        if (res.data.code === 200) {
          this.$message.success("验证码获取成功" + res.data.data.captcha);
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    // 点击提交表单
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        window.console.log(valid)
        window.console.log(register)
        if (valid) {
          register({
            username: this.form.username,
            password: this.form.password,
            phone: this.form.phone,
            email: this.form.email,
            avatar: this.form.avatar,
            rcode: this.form.rcode
          }).then(res => {
            window.console.log(res)
            if (res.data.code === 200) {
              // 关闭对话框
              this.dialogFormVisible = false
              this.$message.success('恭喜你，注册成功啦')
              this.reset(formName)
            } else {
              this.$messag.error(res.data.message)
            }
          })
        } else {
          this.$message.error('验证失败')
        }
      })
      this.dialogFormVisible = false
    }
  },
  components: {}
};
</script>

<style lang="less">
  .register-dialog {
    .el-dialog__header {
      background: linear-gradient(to right, #0dbfef, #1792f8);
    }
    .el-dialog__title {
      color: white;
    }
    .register-box {
      height: 40.8px;
      .register-code {
        height: 40.8px;
        width: 100%;
      }
    }
    .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader {
      text-align: center;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409eff;
    }

    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }

    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
  }
</style>
